print("App is starting...")
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from werkzeug.security import generate_password_hash, check_password_hash
import webbrowser
import sqldb

app = Flask(__name__)
app.secret_key = 'test123'  # 测试用简单密钥
# 模拟用户数据库（测试用）
users = {
    "a": {
        "password_hash": generate_password_hash("1"),  # 密码自动加密
        "id": 1,
        "role": "super_admin"  # 超级管理员角色
    },
    "stock_manager": {
        "password_hash": generate_password_hash("1"),  # 密码自动加密
        "id": 2,
        "role": "stock_manager"  # 库存管理员角色
    }
}



@app.route('/')
def home():
    return redirect(url_for('login'))

# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = users.get(username)
        if user and check_password_hash(user['password_hash'], password):
            session['user_id'] = user['id']
            session['username'] = username
            session['role'] = user['role']
            return redirect(url_for('index'))
        return render_template('login.html', error="用户名或密码错误")

    return render_template('login.html')

# 退出登录
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

@app.route('/index/')
# @login_required
def index():
    return render_template('goods.html')


# 超级管理员管理页面
@app.route('/admin/manage_users')
# @login_required
# @super_admin_required
def manage_users():
    stock_managers = [user for user, info in users.items() if info['role'] == 'stock_manager']
    return render_template('manage_users.html', stock_managers=stock_managers)


# 修改库存管理员密码
@app.route('/admin/change_password', methods=['POST'])
# @login_required
# @super_admin_required
def change_password():
    username = request.form.get('username')
    new_password = request.form.get('new_password')
    if username in users and users[username]['role'] == 'stock_manager':
        users[username]['password_hash'] = generate_password_hash(new_password)
        return jsonify({"code": 0, "msg": "The password modification was successful."})
    return jsonify({"code": 1, "msg": "The modification failed. The user does not exist or is not the inventory manager"})

@app.route('/other/')
def other():
    return render_template('records.html')


@app.route('/count/')
def count():
    return render_template('count.html')


@app.route('/data/goods/')
def getgoods():
#data数据要以这种方式命名是为了LAYUI的数据要求
    data = {"code": 0, "msg": ""}
    name = request.args.get('search_name') or ''
    model = request.args.get('search_model') or ''
    process = request.args.get('search_process') or ''
    lst = sqldb.select_goods(name, model, process)
    for i in lst:
        i['needbuy'] = int(i['safenumber']) - int(i['number'])
    data['count'] = len(lst)
    data['data'] = lst
    return data


@app.route('/data/records/')
def getrecords():
    data = {"code": 0, "msg": ""}
    lst = sqldb.select_records()
    data['count'] = len(lst)
    data['data'] = lst
    return data


@app.route('/data/counts/')
def getcounts():
    # process = request.args.get('process')
    inorout = request.args.get('inorout')
    date1 = request.args.get('date1')
    date2 = request.args.get('date2') + " 23:59:59"
    data = {"code": 0, "msg": ""}
    lst = sqldb.count_goods(inorout, date1, date2)
    data['count'] = len(lst)
    data['data'] = lst
    return data


@app.route('/op/<kind>')
def op(kind):
    if kind == 'in':
        id = request.args.get('in_id')
        change = request.args.get('in_change')
        people = request.args.get('in_people')
        sqldb.insert_records(id, 1, change, people)
    elif kind == 'out':
        id = request.args.get('out_id')
        change = request.args.get('out_change')
        people = request.args.get('out_people')
        sqldb.insert_records(id, 0, change, people)

    elif kind == 'add':
        name = request.args.get('add_name')
        model = request.args.get('add_model')
        factory = request.args.get('add_factory') or ''
        process = request.args.get('add_process')
        price = request.args.get('add_price') or 0
        sqldb.insert_goods(name, model, factory, process, price)
    elif kind == 'del':
        id = request.args.get('del_id')
        sqldb.del_goods(id)
    elif kind == 'edit':
        # 更新物品信息
        id = request.args.get('edit_id')
        name = request.args.get('edit_name')
        model = request.args.get('edit_model')
        process = request.args.get('edit_process')
        factory = request.args.get('edit_factory') or ''
        price = request.args.get('edit_price') or 0
        safe_number = request.args.get('edit_safenumber') or 0
        sqldb.update_goods(id, name, model, process, factory, price,safe_number)

    return jsonify()


@app.route('/data/<kind>')
def get_names(kind):
    data = {"code": 0, "msg": ""}
    lst = sqldb.get_names(kind)
    # print(lst)
    for i in list(lst):
        if i[kind] is None:
            lst.pop(lst.index(i))

    data['count'] = len(lst)
    data['data'] = lst
    return data


@app.route('/error/')
def error():
    return "500"


@app.route('/notifications/')
def notifications():
    return render_template('notifications.html')


@app.route('/data/notifications/')
def get_notifications():
    data = {"code": 0, "msg": ""}
    # 获取所有通知信息，未读信息排在前面
    lst = sqldb.get_all_notifications()
    data['count'] = len(lst)
    data['data'] = lst
    return data


@app.route('/mark_notification_as_read/<int:notification_id>')
def mark_notification_as_read_route(notification_id):
    sqldb.mark_notification_as_read(notification_id)
    return jsonify({"code": 0, "msg": "The notice has been marked as read"})


if __name__ == '__main__':
    webbrowser.open("http://127.0.0.1:5000/")
    app.run()
